<?php
/**
 * 内存共享
 * 使用shmop扩展管理内存
 * hash映射并不完备肯键值冲突，数据不可存储过多
 */
class mem
{

	/**
	 * 存储接口
	 * @method set
	 * @param  [type] $name  [description]
	 * @param  [type] $value [description]
	 * @author NewFuture
	 */
	public static function set($name, $value)
	{
		$id = self::createId($name);
		self::delete($id);
		// var_dump($id);
		$data = serialize($value);
		$sid  = @shmop_open($id, 'c', 0644, strlen($data));
		if ($sid)
		{
			return shmop_write($sid, $data, 0);
		}
	}

	/**
	 * 获取接口
	 * @method get
	 * @param  [type] $name [description]
	 * @return [type]       [description]
	 * @author NewFuture
	 */
	public static function get($name)
	{

		$sid = @shmop_open(self::createId($name), 'a', 0, 0);
		if ($sid)
		{
			$size = shmop_size($sid);
			$data = shmop_read($sid, 0, $size);
			shmop_close($sid);
			return unserialize($data);
		}
		else
		{
			return null;
		}
	}

	/**
	 * 删除接口
	 * @method del
	 * @param  [type] $name [description]
	 * @return [type]       [description]
	 * @author NewFuture
	 */
	public static function del($name)
	{
		return delete(self::createId(($name)));
	}

	/**
	 * 生成唯一ID标识
	 * 暂时采用adler32进行hash
	 * @method createId
	 * @param  [type]    $key [description]
	 * @return [type]         [description]
	 * @author NewFuture
	 */
	private static function createId($name)
	{
		return '0x' . hash('adler32', $name);
	}

	/**
	 * 删除数据
	 * @method delete
	 * @param  [type] $id [description]
	 * @return [type]     [description]
	 * @author NewFuture
	 */
	private static function delete($id)
	{
		$sid = @shmop_open($id, 'a', 0, 0);
		if ($sid)
		{
			shmop_delete($sid);
			shmop_close($sid);
		}
	}
}